package com.example.petstoreservice.controller;

import com.example.petstoreservice.entity.Result;
import com.example.petstoreservice.entity.User;
import com.example.petstoreservice.service.UserService;
import com.example.petstoreservice.utils.JwtUtil;
import com.example.petstoreservice.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/insert")
    public Result<?> insertUser(@RequestBody User user) {
        // 设置用户的 enable 为 1
        user.setEnable(1);

        Result<User> res = new Result<>();
        if (userService.insertUser(user)) {
            res.setData(user);
            res.setStatusCode("200");
            res.setMessage("注册成功");
            return res;
        } else {
            return Result.fail();
        }
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> credentials) {
        Result<User> res = new Result<>();
        String username = credentials.get("username");
        String password = credentials.get("password");

        // 根据用户名查询用户
        User loginUser = userService.findByUsername(username);

        // 判断用户是否存在
        if (loginUser == null) {
            return Result.fail("用户名错误");
        } else if (loginUser.getEnable() == 0) {
            return Result.fail("当前用户不可用");
        }

        // 判断密码是否正确
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userType", loginUser.getUserType());
            claims.put("username", loginUser.getUsername());
            claims.put("enable", loginUser.getEnable());
            String token = JwtUtil.genToken(claims);

            loginUser.setToken(token);
            res.setData(loginUser);
            res.setMessage("登陆成功");
            res.setStatusCode("200");

            return res;
        }
        return Result.fail("密码错误");
    }

    @PostMapping("/{username}/changePassword")
    public Result<?> changePassword(
            @PathVariable String username,
            @RequestBody Map<String, String> passwords
    ) {
        String currentPassword = passwords.get("currentPassword");
        String newPassword = passwords.get("newPassword");

        // 根据用户名查询用户
        User user = userService.findByUsername(username);

        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 验证当前密码是否正确
        if (!Md5Util.checkPassword(currentPassword, user.getPassword())) {
            return Result.fail("当前密码不正确");
        }

        // 调用UserService的updatePassword方法
        int updateResult = userService.updatePassword(username, newPassword);

        if (updateResult == 2) {
            return Result.success("密码修改成功");
        } else if (updateResult == 1) {
            return Result.fail("新密码与原密码相同");
        } else if (updateResult == 0) {
            return Result.fail("用户不存在");
        } else {
            return Result.fail("密码修改失败");
        }
    }

    @PostMapping("/updateUser")
    public Result<?> updateUser(@RequestBody User user) {
        System.out.println("正在更新用户: " + user);

        // 获取当前用户信息
        User currentUser = userService.findByUsername(user.getUsername());

        if (currentUser == null) {
            return Result.fail("用户不存在");
        }

        if (user.getNickname() != null) {
            currentUser.setNickname(user.getNickname());
        }
        if (user.getIntroduction() != null) {
            currentUser.setIntroduction(user.getIntroduction());
        }
        if (user.getSex() != null) {
            currentUser.setSex(user.getSex());
        }
        if (user.getAge() != 0) {
            currentUser.setAge(user.getAge());
        }
        if (user.getScore() != 0) {
            currentUser.setScore(user.getScore());
        }
        if (user.getUserType() != 0) {
            currentUser.setUserType(user.getUserType());
        }

        // 保留其他字段
        currentUser.setUserType(currentUser.getUserType());
        currentUser.setEnable(currentUser.getEnable());

        if (userService.updateUser(currentUser)) {
            return Result.success("修改成功");
        } else {
            return Result.fail();
        }
    }

    @GetMapping("/getUserInfo/{username}")
    public Result<User> getUserInfo(@PathVariable String username) {
        User user = userService.findByUsername(username);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.fail("用户不存在");
        }
    }

    @PostMapping("/delete/{username}")
    public Result<?> deleteUser(@PathVariable String username) {
        if (userService.deleteUser(username)) {
            return Result.success("账户注销成功");
        } else {
            return Result.fail("账户注销失败");
        }
    }
}
